/*
 * Copyright (c) 2008 by Chances.
 * $CVSHeader$
 * $Author: liujian $
 * $Date: 2009/11/09 01:11:25 $
 * $Revision: 1.1 $
 */
package chances.epg.commons.utils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * 截取给定宽度（字节的宽度）中英文字符串.
 * 
 * @author <a href="mailto:chenjian@chances.com.cn">chenjian</a>
 */
public class TextUtils {
    /**
     * 根据长度截取字符串(该字符串不含HTML标签).
     * 
     * @param str
     *            原始字符串
     * @param length
     *            截取长度
     * @return
     */
    public static List<String> cutString(String str, int length) {
        List<String> result = new ArrayList<String>();
        // 得到页数
        int page = str.length() / length;
        if (str.length() % length > 0) {
            page++;
        }
        // 把每页添加到List中
        for (int i = 0; i < page; i++) {
            int indexBegin;
            if (i == 0) {
                indexBegin = 0;
            } else {
                indexBegin = i * length - 1;
            }
            int indexEnd = (i + 1) * length - 1;
            if (i == page - 1) { // 如果是最后一页
                result.add(str.substring(indexBegin));
            } else {
                result.add(str.substring(indexBegin, indexEnd));
            }
        }
        return result;
    }

    public static String replace(String origin, String oldString,
            String newString) {
        if (!origin.contains(oldString)) {
            return origin;
        }
        int i = origin.indexOf(oldString);
        String beforeString = origin.substring(0, i);
        String afterString = origin.substring(i + oldString.length());
        origin = beforeString + newString + afterString;
        origin = replace(origin, oldString, newString);
        return origin;
    }

    /**
     * 过滤文本中的标签.
     * 
     * @param content
     * @return
     */
    public static String filterHtmlTag(String content,boolean withBr) {
        String result = new String(content);
        result = result.replaceAll("</p>", "\b");
        result = result.replaceAll("<br>", "\b");
        result = result.replaceAll("<br[ ]*/>", "\b");
        result = result.replaceAll("<[^>]*>", "");
        result = result.replaceAll("\b", "<br>");       
        result = result.replaceAll("\n", "<br>");
        result = result.replaceAll("\r", "<br>");
        result = result.replaceAll("\t", "");
        char[] archar = result.toCharArray();
        for (int i = 0; i < archar.length; i++) {
            if (archar[i] == 160) {
                archar[i] = ' ';
            }
        }
        result = new String(archar);
        
        result = result.replaceAll("　", "  ");//1个全角空格，变2个半角空格
        result = result.replaceAll(" *<br>", "<br>");//去除<br>前的空格
        result=result.replaceAll("  ", "　");//2个半角空格还原成1个全角空格
        
        while (result.startsWith("<br>")) {
            result = result.replaceFirst("<br>", "");
        }
        while (result.endsWith("<br>")) {
            result = result.substring(0, result.lastIndexOf("<br>"));
        }
        while (result.endsWith("<br/>")) {
            result = result.substring(0, result.lastIndexOf("<br/>"));
        }
        if (!withBr){
        		result = result.replaceAll("<br>", "");
        }
        return result;
    }

    /**
     * 将一段文字根据字数截开.<br>
     * 该文字只包括br标签(不包括其它HTML标签，及"\r\n")<br>
     * 按段落截取，段落超过字数则从中截取
     * 
     * @param content
     * @param numChar
     * @return
     */
    public static List<String> pageParagraph(String content, int numChar) {
        List<String> result = new ArrayList<String>();
        String[] pars = content.split("<br>");

        // 处理字数超过规定数目的段落
        List<String> parList = new ArrayList<String>();
        for (String par : pars) {
            if (par.length() > numChar) {
                parList.addAll(TextUtils.cutString(par, numChar));
            } else {
                parList.add(par);
            }
        }

        StringBuffer part = new StringBuffer();
        for (String par : parList) {
            if (part.length() > 0 && (part.length() + par.length() > numChar)) {
                result.add(part.toString());
                part = new StringBuffer(par + "<br>");
            } else {
                part.append(par + "<br>");
            }
        }
        result.add(part.toString()); // 添加最后一页内容
        return result;
    }

    public String easyTitle(String title, int len) {
        String result = "";
        if (title.length() > len) {
            result = title.substring(0, len) + "...";
        } else {
            result = title;
        }
        return result;
    }

    public static String[] getPageStrings(String article, int meiHangZiShu,
            int hangShu,boolean need2Blanks,String dotdotdot) {
        String[] pageStrings = createParagraph(article, meiHangZiShu, hangShu,need2Blanks,dotdotdot);
        return pageStrings;
    }

    private static String[] createParagraph(String article, int meiHangZiShu,
            int hangShu,boolean need2Blank,String dotdotdot) {
        List<String> cols = new ArrayList<String>();
        
        String[] paragraphs = article.split("<br>");
        for (String paragraph : paragraphs) {
            if (StringUtils.isBlank(paragraph)) {
                continue;
            }
            if (need2Blank){
                paragraph = "　　" + paragraph.trim();
            }else{
                paragraph =  paragraph.trim();
            }
            int length=0;
            try {
                length = paragraph.getBytes("GB2312").length;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (meiHangZiShu == 0)
            {
                if (need2Blank)
                    return new String[]{"　　"+article};
                else
                    return new String[]{article};
            }
            int col = length / (meiHangZiShu * 2);
            if (length % (meiHangZiShu * 2) != 0) {
                col += 1;
            }
            if (col == 1) {
                paragraph=subString(paragraph, meiHangZiShu * 2,dotdotdot,hangShu);
                cols.add(paragraph );//+ "<br>"
            } else {
                while (StringUtils.isNotEmpty(paragraph)) {
                    String temp = subString(paragraph, meiHangZiShu * 2,dotdotdot,hangShu);
                    if ("".endsWith(temp)){
                         break;
                    }
                    if(hangShu==1)
                        paragraph="";
                    else
                        paragraph = StringUtils.replace(paragraph, temp, "", 1);
                    cols.add(new String(temp));

                }
            }
        }
        
        if (hangShu<cols.size()){
            String[] rs = new String[hangShu];
            for(int i=0;i<hangShu;i++){
                rs[i] = cols.get(i);
            }
            return rs;
        }else{
            return cols.toArray(new String[0]);
        }
    }

    // 以下处理文章的截取

    public static String preproccess(String article) {
        article = article.replaceAll("(<br>)+", "<br>"); // 多个换行处理成一个
        article = article.replaceAll("　","  ");//将1个全角空格转换为2个半角空格
        article = article.trim(); // 1、将段首的半角空格去掉
        article = article.replaceAll("<br> *", "<br>"); // 2、将段首的半角空格去掉
        article =article.replaceAll("  ", "　"); //将2个半角空格还原成1个全角空格
        return article;
    }
    
    public static String[] getPageStringsByChineseCharNumber(String article,int chineseCharNumber,boolean need2Blanks,String dotdotdot) {
        int meiHangZiShu = chineseCharNumber;
        return getPageStrings(article, meiHangZiShu, 1,need2Blanks,dotdotdot);
    }

    /**
     * 截取文字长度.
     * 
     * @param value
     *            待截取文本
     * @param length
     *            截取长度
     * @return
     */
    public static String subString(String value, int length,String dotdotdot,int hangShu) {
        String result = value;
        if (dotdotdot == null){
        	dotdotdot = "";
        }
        int dotLength=0;
        int strLength = 0;
        if(hangShu ==1)
        {
            try {
                dotLength=dotdotdot.getBytes("GB2312").length;
                strLength=value.getBytes("GB2312").length;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
           
        }
        else
        {
            dotdotdot="";
            dotLength=0;
        }
        if (Math.abs(length - strLength) <= 1) return value;
        
        length=length-dotLength;
        for (int i = 0; i < value.length(); i++) {
            if (value.charAt(i) > 128) {
                length -= 2;
            } else {
                length -= 1;
            }
            if (length < 0) {
                result = value.substring(0, i);
                break;
            }
        }
        if (result.equals(value)) return result;
        return result+dotdotdot;
    }
    
 

}